<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-4-3
 */

namespace app\api\controller\v1;

use think\Db;
use think\Request;

class Users extends Base
{
    public $users;
    public $users_id;

    /**
     * 初始化操作
     */
    public function _initialize()
    {
        parent::_initialize();
        $this->users = $this->getUser();   // 用户信息
        $this->users_id = !empty($this->users['users_id']) ? intval($this->users['users_id']) : null;
        if (empty($this->users_id)) $this->error('请先登录');
    }

    /**
     * 首页
     */
    public function index()
    {
        $data = $this->apiLogic->taglibData();
        $this->renderSuccess($data);
    }

    //获取留言列表
    public function guestbook_list()
    {
        if (IS_AJAX) {
            $list = model('v1.User')->guestbookList();
            return $this->renderSuccess(compact('list'));
        }
        $this->error('请求错误！');


    }

    //获取我的预约详情
    public function get_book_detail()
    {
        if (IS_AJAX) {
            $param = input('param.');
            $list = model('v1.User')->GetMyBookDetail($param);

            return $this->renderSuccess(compact('list'));
        }
        $this->error('请求错误！');
    }

    //取消预约
    public function cancel_book()
    {
        if (IS_AJAX) {
            $aid = input('param.aid/d', 0);
            if (empty($aid)) {
                $this->error('缺少参数aid！');
            }
            $r = Db::name('guestbook')
                ->where(['aid' => $aid, 'users_id' => $this->users_id])
                ->delete();
            if (false !== $r) {
                Db::name('guestbook_attr')->where('aid', $aid)->delete();
                $this->success('取消成功！');
            } else {
                $this->error('取消失败！');
            }
        }
        $this->error('请求错误！');
    }


    /**
     * 保存评价
     * @return array
     */
    public function save_comment()
    {
        if (IS_AJAX_POST) {
            $post = input('post.');
            return model('v1.Shop')->getSaveComment($post, $this->users_id);
        }
        $this->error('评价失败！');
    }

    /**
     * 用户领取优惠券
     */
    public function get_coupon()
    {
        if (IS_AJAX) {
            $coupon_id = input('param.coupon_id/d',0);
            $where = [
                'coupon_id' => $coupon_id,
            ];
            //查询优惠券信息,结束发放时间/库存
            $status = Db::name('shop_coupon')->where($where)->value('status');
            if (!empty($status)){
                $end_date = getTime();
                $update = [
                    //默认给一年的有效期
                    'end_date' => strtotime("+12 month",$end_date),
                    'update_time'=>getTime()
                ];
                Db::name('shop_coupon')->where($where)->update($update);
            }

            $coupon = Db::name('shop_coupon')->where($where)->find();
            if (!empty($coupon)) {
                if (1 > $coupon['coupon_stock']) {
                    $this->error('优惠券库存不足！');
                }
                if (getTime() > $coupon['end_date']) {
                    $this->error('优惠券发放已结束！');
                }
                //判断会员权限
                $coupon['level_id'] = explode(',',$coupon['level_id']);
                $users_level = Db::name('users')->where('users_id',$this->users_id)->value('level');
                if (!in_array($users_level,$coupon['level_id'])){
                    $this->error('您的会员等级不可领取！');
                }

                $where['users_id'] = $this->users_id;
                $where['use_status'] = ['in',[0,1]];
                //查询优惠券 是否存在 领取限制  0-没有领取限制
                if ($coupon['limit'] > 0) {
                    $count = Db::name('shop_coupon_use')->where($where)->count();
                    if ($count >= $coupon['limit']) {
                        $this->error('已达领取上限！');
                    }
                }

                $insert['coupon_id'] = $coupon_id;
                $insert['coupon_code'] = $coupon['coupon_code'];
                $insert['users_id'] = $this->users_id;
                $insert['use_status'] = 0;
                $insert['get_time'] = getTime();
                $insert['add_time'] = getTime();
                $insert['update_time'] = getTime();
                //根据使用期限不同插入开始/结束使用时间
                if (1 == $coupon['use_type']) {//固定期限
                    $insert['start_time'] = $coupon['use_start_time'];
                    $insert['end_time'] = $coupon['use_end_time'];
                } else if (2 == $coupon['use_type']) {//当日开始N天有效
                    $insert['start_time'] = strtotime(date("Y-m-d", time()));
                    $insert['end_time'] = $insert['start_time'] + $coupon['valid_days'] * 86400;
                } else if (3 == $coupon['use_type']) {//次日开始N天有效
                    $insert['start_time'] = strtotime(date("Y-m-d", time())) + 86400;
                    $insert['end_time'] = $insert['start_time'] + $coupon['valid_days'] * 86400;
                } else if (4 == $coupon['use_type']) {//永久有效
                    $insert['start_time'] = strtotime(date("Y-m-d", time()));
                    $insert['end_time'] = strtotime("+10 year");//10年
                }
                if (!empty($insert)) {
                    $use_insert = Db::name('shop_coupon_use')->insert($insert);
                    if (!empty($use_insert)) {
                        eyou_set_is_real($this->users_id);//设为真实用户
                        //-库存 +领取
                        Db::name('shop_coupon')->where('coupon_id', $coupon_id)->update(['coupon_stock' => Db::Raw('coupon_stock-1'), 'coupon_geted' => Db::Raw('coupon_geted+1'), 'update_time' => getTime()]);
                        //返回数据
                        $coupon_data = Db::name('shop_coupon')
                            ->where('coupon_id', $coupon_id)
                            ->find();
                        $coupon_data['get'] = Db::name('shop_coupon_use')->where('coupon_id', $coupon_id)->where('users_id', $this->users_id)->find();
                        $this->success('领取成功！','',['coupon_data'=>$coupon_data]);
                    }
                }
            }
        }
        $this->error('优惠券领取失败！');
    }

    /**
     * 获取我的优惠券
     */
    public function get_my_coupon($dataType)
    {
        $list = model('v1.Shop')->GetMyCouponList($this->users_id, $dataType);

        return $this->renderSuccess(compact('list'));
    }

    /**
     * 领券中心
     */
    public function get_coupon_center()
    {
        $list = model('v1.Shop')->GetCouponCenter($this->users_id);

        return $this->renderSuccess(compact('list'));
    }

    /**
     * 收藏(喜欢)/取消
     * 收藏 type users_collection
     * 喜欢 type users_like
     */
    public function get_collect()
    {
        if (IS_AJAX_POST) {
            $aid = input('param.aid/d');
            $type = input('param.type/s', 'users_collection');
            $success = '已收藏';
            $cancel = '已取消';
            if ('users_collection' != $type) {
                $success = 'success';
            } else {
                $cancel = 'cancel';
            }
            if (empty($aid)) {
                $this->error('缺少文档ID！');
            }
            $count = Db::name($type)->where([
                'aid' => $aid,
                'users_id' => $this->users_id,
            ])->count();
            if (empty($count)) {
                $addSave = Db::name('archives')->field('aid,channel,typeid,title,litpic')->where('aid', $aid)->find();
                if (empty($addSave)) {
                    $this->error('文档不存在！');
                }
                $addSave['add_time'] = getTime();
                $addSave['users_id'] = $this->users_id;
                $r = Db::name($type)->insert($addSave);
                if (!empty($r)) {
                    if ('users_collection' == $type) {
                        $ret_data = ['is_collect' => 1];
                    } else if ('users_like' == $type) {
                        $ret_data = ['is_like' => 1];
                    }
                    $this->success($success, null, $ret_data);
                }
            } else {
                // 如果是购物车收藏则执行
                $source = input('param.source/s', '');
                if (!empty($source) && 'shopCart' === $source) $this->success('已收藏');
                // 其他收藏操作执行
                $r = Db::name($type)->where(['aid' => $aid, 'users_id' => $this->users_id])->delete();
                if (!empty($r)) {
                    if ('users_collection' == $type) {
                        $ret_data = ['is_collect' => 0];
                    } else if ('users_like' == $type) {
                        $ret_data = ['is_like' => 0];
                    }
                    $this->success($cancel, null, $ret_data);
                }
            }
        }
        $this->error('请求错误！');
    }

    //修改头像/昵称/手机号/生日/性别/个人简介
    public function save_user_info()
    {
        if (IS_AJAX_POST) {
            $head_pic = input('param.head_pic/s');
            $nickname = input('param.nickname/s');
            $nickname = filterNickname($nickname);
            $sex = input('param.sex/d');
            $birthday = input('param.birthday/s');
            $intro = input('param.intro/s');
            $mobile = input('param.mobile/s');
            if (!empty($head_pic) || !empty($nickname) || !empty($mobile)) {
                $update = ['update_time' => getTime()];
                if (!empty($head_pic)) {
                    $head_pic = preg_replace('/^(([^\:]+):)?(\/\/)?([^\/\:]*)(.*)$/i', '${5}', $head_pic);;
                    if (!is_http_url($head_pic)){
                        $head_pic = func_thumb_img($head_pic, 100, 100);
                    }
                    $update['head_pic'] = $head_pic;
                }
                if (!empty($nickname)) {
                    $update['nickname'] = $nickname;
                    $update['is_nickname'] = 1;
                }
                if (!empty($sex)) {
                    $update['sex'] = $sex;
                }
                if (!empty($intro)) {
                    $update['intro'] = $intro;
                }
                if (!empty($birthday)) {
                    $update['birthday'] = strtotime($birthday);
                }
                if (!empty($mobile)) {
                    $is_mobile = check_mobile($mobile);
                    if (!$is_mobile) {
                        $this->error('手机号格式不正确!');
                    }
                    $update['mobile'] = $mobile;
                    $update['is_mobile'] = 1;
                }
                $r = Db::name('users')->where(['users_id' => $this->users_id])->update($update);
                if (!empty($r)) {
                    //绑定昵称则设为真是用户
                    if (!empty($update['is_nickname'])){
                        eyou_set_is_real($this->users_id);
                    }
                    GetUsersLatestData($this->users_id, 'applets');
                    $this->success('保存成功');
                }
            }
            $this->error('保存失败');
        }
    }

    // 处理会员余额方法(集合方法)
    public function HandleUserMoneyAction()
    {
        if (IS_AJAX) {
            // 传入参数
            $param = input('param.');

            // 处理传入的参数
            $param['users_id'] = intval($this->users_id);
            $param['moneyid'] = !empty($param['moneyid']) ? intval($param['moneyid']) : 0;
            $param['usersMoney'] = !empty($param['usersMoney']) ? strval($param['usersMoney']) : 0;//充值金额,现在没用上,是直接去充值活动表根据id查询的
            $param['order_number'] = !empty($param['order_number']) ? strval($param['order_number']) : '';
            $param['type_id'] = !empty($param['type_id']) ? strval($param['type_id']) : 0;

            $v1ShopModel = model('v1.Shop');
            // 判断执行操作
            $action = !empty($param['action']) ? strval($param['action']) : '';
            if ('details' == $action) {
                $v1ShopModel->getUsersMoneyDetails($this->users, $param);
            } else if ('recharge' == $action) {
                // 会员余额充值
                $v1ShopModel->getUsersMoneyRecharge($param);
            } else if ('rechargePay' == $action) {
                // 会员余额充值后续处理
                $v1ShopModel->getUsersMoneyRechargePay($param);
            }
        }
    }

    /**
     * 添加转发记录
     */
    public function set_forward()
    {
        if (IS_AJAX) {
            $users_id = $this->users_id;
            $aid = input('param.aid/d');
            if (empty($aid)) {
                $this->error('缺少文档ID!');
            }
            //查询标题模型缩略图信息
            $arc = Db::name('archives')
                ->field('aid,channel,typeid,title,litpic')
                ->find($aid);
            if (!empty($arc)) {
                $arc['users_id'] = $users_id;
                $arc['add_time'] = getTime();
                $arc['update_time'] = getTime();
                Db::name('users_forward')->insert($arc);
                $this->success('保存成功');
            }
        }
        $this->error('请求错误！');
    }

    /**
     * 留言栏目
     */
    public function guestbook($typeid = '')
    {
        $param = input('param.');
        if (IS_POST && !isset($param['apiGuestbookform'])) {
            $post = input('post.');
            $typeid = !empty($post['typeid']) ? intval($post['typeid']) : $typeid;
            if (empty($typeid)) {
                $this->error('post接口缺少typeid的参数与值！');
            }

            /*留言间隔限制*/
            $channel_guestbook_interval = tpSetting('channel_guestbook.channel_guestbook_interval');
            $channel_guestbook_interval = is_numeric($channel_guestbook_interval) ? intval($channel_guestbook_interval) : 60;
            if (0 < $channel_guestbook_interval) {
                $map = array(
                    'ip' => clientIP(),
                    'typeid' => $typeid,
                    'add_time' => array('gt', getTime() - $channel_guestbook_interval),
                );
                $count = Db::name('guestbook')->where($map)->count('aid');
                if (!empty($count)) {
                    $this->error("同一个IP在{$channel_guestbook_interval}秒之内不能重复提交！");
                }
            }
            /*end*/

            // 提取表单令牌的token变量名
            $token = '__token__';
            foreach ($post as $key => $val) {
                if (preg_match('/^__token__/i', $key)) {
                    $token = $key;
                    continue;
                }
            }

            //判断必填项
            foreach ($post as $key => $value) {
                if (stripos($key, "attr_") !== false) {
                    //处理得到自定义属性id
                    $attr_id = substr($key, 5);
                    $attr_id = intval($attr_id);
                    $ga_data = Db::name('guestbook_attribute')->where([
                        'attr_id' => $attr_id,
                    ])->find();
                    if ($ga_data['required'] == 1 && empty($value)) {
                        $this->error($ga_data['attr_name'] . '不能为空！');
                    }

                    if ($ga_data['validate_type'] == 6 && !empty($value)) {
                        $pattern = "/^1\d{10}$/";
                        if (!preg_match($pattern, $value)) {
                            $this->error($ga_data['attr_name'] . '格式不正确！');
                        }
                    } elseif ($ga_data['validate_type'] == 7 && !empty($value)) {
                        $pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/i";
                        if (preg_match($pattern, $value) == false) {
                            $this->error($ga_data['attr_name'] . '格式不正确！');
                        }
                    }
                }
            }

            $newData = array(
                'typeid' => $typeid,
                'users_id' => $this->users_id,
                'channel' => 8,
                'ip' => clientIP(),
                'add_time' => getTime(),
                'update_time' => getTime(),
            );
            $data = array_merge($post, $newData);

            /*表单令牌*/
            $token_value = !empty($data[$token]) ? $data[$token] : '';
            $session_path = \think\Config::get('session.path');
            $session_file = ROOT_PATH . $session_path . "/sess_" . str_replace('__token__', '', $token);
            $filesize = @filesize($session_file);
            if (file_exists($session_file) && !empty($filesize)) {
                $fp = fopen($session_file, 'r');
                $token_v = fread($fp, $filesize);
                fclose($fp);
                if ($token_v != $token_value) {
                    $this->error('表单令牌无效！');
                }
            } else {
                $this->error('表单令牌无效！');
            }
            /*end*/

            $guestbookRow = [];
            /*处理是否重复表单数据的提交*/
            $formdata = $data;
            foreach ($formdata as $key => $val) {
                if (in_array($key, ['typeid']) || preg_match('/^attr_(\d+)$/i', $key)) {
                    continue;
                }
                unset($formdata[$key]);
            }
            $md5data = md5(serialize($formdata));
            $data['md5data'] = $md5data;
            $guestbookRow = M('guestbook')->field('aid')->where(['md5data' => $md5data])->find();
            /*--end*/

            $aid = !empty($guestbookRow['aid']) ? $guestbookRow['aid'] : 0;
            if (empty($guestbookRow)) { // 非重复表单的才能写入数据库
                $aid = M('guestbook')->insertGetId($data);
                if ($aid > 0) {
                    $res = model('v1.Api')->saveGuestbookAttr($post, $aid, $typeid);
                    if ($res) {
                        $this->error($res);
                    }
                }
            } else {
                // 存在重复数据的表单，将在后台显示在最前面
                Db::name('guestbook')->where('aid', $aid)->update([
                    'add_time' => getTime(),
                    'update_time' => getTime(),
                ]);
            }
            @unlink($session_file);
            $this->renderSuccess(['aid' => $aid], '提交成功');
        }
        $this->error('请求错误！');
    }

    //点赞
    public function ask_like()
    {
        model('v1.Ask')->askLike($this->users);
    }

    //提交问题
    public function add_ask()
    {
        model('v1.Ask')->addAsk($this->users);
    }

    //提交回答
    public function add_answer()
    {
        model('v1.Ask')->addAnswer($this->users);
    }
    
    //清空足迹
    public function clear_footprint()
    {
        $users_id = $this->users_id;
        Db::name('users_footprint')->where('users_id',$users_id)->delete();
        $this->success('success');
    }

    //积分首页
    public function score_index()
    {
        $score = getUsersConfigData('score');
        $data['score_config'] = $score;  // 积分名字score_name
        $data['score'] = $this->users['scores'];  // 积分名字score_name
        $data['rule'] = Db::name('users_score')->where(['users_id'=>$this->users_id])->group('rule')->field('sum(score) as total,rule')->getAllWithIndex('rule');

        $data['today_get'] = Db::name('users_score')->where(['users_id'=>$this->users_id,'rule'=>2])->whereTime('add_time','today')->sum('score');
        if (!empty($score['score_reg_status']) && 1 == $score['score_reg_status']){
            //注册送
            $data['reg_get'] = Db::name('users_score')->where(['users_id'=>$this->users_id,'type'=>6])->count();
        }
        if (!empty($score['score_signin_status']) && 1 == $score['score_signin_status']){
            //签到
            $data['sign_get'] = Db::name('users_score')->where(['users_id'=>$this->users_id,'type'=>1])->whereTime('add_time','today')->count();
        }

        $this->renderSuccess($data);
    }

    /**
     * 积分签到
     */
    public function sign()
    {
        //今日是否已经签到
        $count = Db::name('users_score')->where(['users_id'=>$this->users_id,'type'=>1])->whereTime('add_time','today')->count();
        if (empty($count)) {
            $score = getUsersConfigData('score');

            $score_data = [
                'type' => 1, //看global的users_score_type_arr
                'users_id' => $this->users_id,
                'score' => $score['score_signin_score'],
            ];
            eyou_give_score($score_data);
            $this->success('签到成功！','',['upgrade'=>1]);
        } else {
            $this->success('今日已签到！');
        }
    }
}